public without sharing class QuoteHandler {

    

    // 报价审批通过以后，业务机会进入方案谈判阶段
    // public static void setOppStatus(List<Quote> newList, Map<Id, Quote> oldMap) {
    //     for (Quote q : newList) {
    //         Quote oldQuote = oldMap.get(q.Id);
    //         if (oldQuote.Status != q.Status && q.Status == '已批准' && q.AdjustTo__c == null) {
    //             // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
    //             Opportunity opp = [select Id, RecordType.Name from Opportunity where Id = :q.OpportunityId];
    //             opp.StageName = '方案谈判';
    //             // opp.SyncedQuoteId = q.Id;
    //             opp.ActiveQuote__c = q.Id;
    //             update opp;

    //             q.IsActive__c = true;
    //             // 自动生成报价单
    //             // String pdfUrl = '/apex/QuoteProductPDF?id=' + q.Id;
    //             // Attachment att = new Attachment(
    //             //     ParentId = q.Id,
    //             //     Name = '报价单.pdf',
    //             //     Body = new PageReference('/apex/QuoteProductPDF?id=' + q.Id).getContent(),
    //             //     ContentType = 'pdf'
    //             // );
    //             // insert att;

    //             // 把其它的报价变为无效
    //             List<Quote> otherQList = [select Id from Quote where OpportunityId = :opp.Id and Id != :q.Id];
    //             if (otherQList.size() > 0) {
    //                 for (Quote oq : otherQList) {
    //                     oq.IsActive__c = false;
    //                 }
    //                 update otherQList;
    //             }
    //         }
    //     }
    // }
    // 调价单审批通过之后，反写之前报价的产品价格
    // public static void writeBackProduct(List<Quote> newList, Map<Id, Quote> oldMap) {
    //     for (Quote q : newList) {
    //         Quote oldQuote = oldMap.get(q.Id);
    //         if (oldQuote.Status != q.Status && q.Status == '已批准' && q.AdjustTo__c != null) {
    //             // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
    //             List<QuoteProduct__c> fromList = [select Id, AdjustTo__c, SalesPrice__c, Quantity__c, Comment__c from QuoteProduct__c where Quote__c = :q.Id];
    //             // List<Id> qpidList = new List<Id>();
    //             Map<Id, QuoteProduct__c> qpMap = new Map<Id, QuoteProduct__c>();
    //             for (QuoteProduct__c qp : fromList) {
    //                 // qpidList.add(qp.AdjustTo__c);
    //                 qpMap.put(qp.AdjustTo__c, qp);
    //             }
    //             List<QuoteProduct__c> toList = [select Id from QuoteProduct__c where Id in :qpMap.keySet()];
    //             for (QuoteProduct__c qp : toList) {
    //                 qp.SalesPrice__c = qpMap.get(qp.Id).SalesPrice__c;
    //                 qp.Quantity__c = qpMap.get(qp.Id).Quantity__c;
    //                 qp.Comment__c = qpMap.get(qp.Id).Comment__c;
    //             }
    //             update toList;
    //         }
    //     }
    // }


    
    //计算明细中是否有自产产品
    public static void calcZc(Map<Id,Quote> qM ){
        Map<Id,String> tMap = new Map<Id,String>();


         Map<Id,Set<Id>> mMap = new Map<Id,Set<Id>>();

        for (Quote q : qM.values() ) {
           
           Set<Id> m = mMap.containsKey(q.OpportunityId  ) ? mMap.get(q.OpportunityId) : new Set<Id>();
           m.add(q.Id );
           mMap.put(q.OpportunityId, m );

        }

        Set<String> companys = new Set<String>();
        Set<String> provinces = new Set<String>();
        Map<String,String> mProvinces= new Map<String,String>();
        for (Opportunity opp : [select Id ,AccountId,Account.InstCompany__c  from Opportunity where Id in: mMap.keySet() ] ) {
           String company = opp.Account.InstCompany__c == null ? 'MKSW' : opp.Account.InstCompany__c; 
           String province = CompanyProvinceUtil.getCompanyCodeAndProvince(company).get(0) ;
           company = CompanyProvinceUtil.transCodeToName(company);
            companys.add(  company) ;
            provinces.add( province);
            mProvinces.put(opp.Id , company+province);
            
        }
        Set<Id> pids = new Set<Id>();
        List<QuoteProduct__c> qpList =  [select Quote__c,Product__c ,Quote__r.OpportunityId , Quantity__c ,Product__r.Brand__c,Product__r.NCCode__c,Product__r.Category1__c ,Product__r.Category0__c   from QuoteProduct__c where Quote__c in:qM.keySet()  ];
       for(QuoteProduct__c qp : qpList ){

            String type  = tMap.get(qp.Quote__c );
           
             if( MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c) || MaccuraBrandUtil.maccura.contains(qp.Product__r.NCCode__c)  || (qp.Product__r.Category1__c == '生化' &&  qp.Product__r.Category0__c == '仪器' ) ) {
                 type = (type == null ||  !type.contains('非自产') ) ? '自产' :'自产/非自产';
                  if( qp.Product__r.Category0__c == '仪器' )pids.add(qp.Product__c);
             }else{
                 type = (  type == null || type == '非自产'  ) ? '非自产' :'自产/非自产';
             }
             tMap.put(qp.Quote__c, type);



       }

       System.debug(pids);
     System.debug(companys); 
     System.debug(provinces);
       Map<String ,Decimal> priceMap = new Map<String,Decimal>();
       for (Price__c p :[select Id,Product__c,Company__c ,Province__c ,InstCost__c from Price__c where Product__c in: pids and Company__c in : companys and Province__c in: provinces and ClosePrice__c != true ] ) {
          priceMap.put(p.Product__c+p.Company__c+p.Province__c, p.InstCost__c);
       }

       

       Map<String,Decimal> mT = new Map<String ,Decimal>();
       for(QuoteProduct__c qp :  qpList ){

          if( MaccuraBrandUtil.maccura.contains(qp.Product__r.Brand__c) || MaccuraBrandUtil.maccura.contains(qp.Product__r.NCCode__c) || (qp.Product__r.Category1__c == '生化' &&  qp.Product__r.Category0__c == '仪器' )) {
               Decimal t =  mT.containsKey(qp.Quote__c)  ? mT.get(qp.Quote__c) : 0;
               String key = qp.Product__c+ mProvinces.get(qp.Quote__r.OpportunityId );
                 System.debug(key);
               t+= (priceMap.get(key) == null ? 0 :priceMap.get(key)) * (qp.Quantity__c == null ? 0 : qp.Quantity__c );
              mT.put(qp.Quote__c,t);
          }
       }
       System.debug(mT);
       for ( Quote q : qM.values() ) {
           q.ZC__c = tMap.get(q.Id);
           q.SelfProductionCostCount__c = mT.get(q.Id );
       }



       



    }
    /**
     * 删除报价的时候也要修改业务机会项目类型
     */
    /*
    public static void setOppProjectType(Map<Id, Quote> oldMap) {
        Set<Id> oidSet = new Set<Id>();
        //Set<Id> newqtidSet = new Set<Id>();
        //Set<String> qpc1Set = new Set<String>();

        for (Quote q : oldMap.values()) {
            if(q.Status !='草案中' || Trigger.isDelete)oidSet.add(q.OpportunityId);
        }
        OppSetProjectTypeHandler.calcOppSetProjectType(oidSet);
       
    }
    */


    public static void setOppStageName(List<Quote> newList, Map<Id, Quote> oldMap) {
        for (Quote q : newList) {
            Quote oldQuote = oldMap.get(q.Id);
            if (oldQuote.Status != q.Status && q.Status == '申请中') {
                // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
                Opportunity opp = [select Id, RecordType.Name,StageName, ExecuteCompany__r.RecordType.DeveloperName from Opportunity where Id = :q.OpportunityId];
                // if (opp.ExecuteCompany__r.RecordType.DeveloperName == 'Maccura') {
                
                if(opp.StageName == '立项'){
                    opp.StageName = '方案谈判';
                // }
                    update opp;
                }
            }
        }
    }


    //报价审批通过以后，把其它同类型的报价变为无效
    public static void disableOtherQuote(List<Quote> newList, Map<Id, Quote> oldMap) {
        
        Id rId = Utils.getRecordTypeIdByDevNameAndObjName('OverseasQuotation', 'Quote');
        System.debug('disableOtherQuote=>'+rId);
        for (Quote q : newList) {
            
            Quote oldQuote = oldMap.get(q.Id);
            if (oldQuote.Status != q.Status && q.Status == '已批准') {
                q.IsActive__c = true;
                // FIXME 审批只会一条一条来，所以允许在for循环里面写soql
                Opportunity opp = [select Id, RecordType.Name, ExecuteCompany__r.RecordType.DeveloperName from Opportunity where Id = :q.OpportunityId];
                // if (opp.ExecuteCompany__r.RecordType.DeveloperName == 'Maccura') {
                //     opp.StageName = '方案谈判';
                // }

                if (q.Type__c == '仪器报价') opp.ActiveQuote__c = q.Id;
                if (q.Type__c == '试剂报价')  opp.ActiveQuoteReagent__c = q.Id;
                
                update opp;

                List<Quote> otherQList = [select Id from Quote where OpportunityId = :q.OpportunityId and Id != :q.Id and Type__c = :q.Type__c and IsActive__c = true];
                if (otherQList.size() > 0) {
                    for (Quote oq : otherQList) {
                        oq.IsActive__c = false;
                    }
                    update otherQList;
                }

                if(q.RecordTypeId == rId)AdjustPriceHandler.adjustAboardQuoteToPriceList(q.Id);
                
            }
        }
    }


    
}